#!/usr/bin/env python
# -*- coding:utf-8 -*-

from conn.MyLogs import MyLogs
from members.beans.MemberPointLevelObj import MemberPointLevelObj


class MemberPointLevelService:
    std_array = {}
    conn = None

    def __init__(self, conn):
        self.conn = conn

    def fetch(self, param):
        try:
            count_sql = f" SELECT count(`id`) FROM `mem_member_point_level` WHERE 1=1 %s"
            fetch_sql = f" SELECT {MemberPointLevelObj.to_string(True)}" \
                        f" FROM `mem_member_point_level` WHERE 1=1 %s "
            where_sql = ""
            if len(param['key']) > 0:
                where_sql = where_sql + f" AND CONCAT(`level`) like CONCAT('%',\'{param['key']}\','%') "

            int_begin = 0
            if int(param['pageNum']) > 1:
                int_begin = (int(param['pageNum']) - 1) * int(param['pageSize'])
            elif int(param['pageNum']) == 1:
                int_begin = 0 * int(param['pageSize'])

            where_sql_no_limit = where_sql + f" ORDER BY `id` DESC"
            where_sql_limit = where_sql_no_limit + f" LIMIT {int_begin}, {int(param['pageSize'])}"
            data_total = self.conn.sql_fetch(count_sql % where_sql_no_limit)
            data_list = self.conn.sql_fetch(fetch_sql % where_sql_limit)
            items = []
            if len(data_list) > 0:
                items = [MemberPointLevelObj.load_db_2_dict(data=item) for item in data_list]
            return {"code": 200, "data": items, "total": data_total[0][0]}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def fetch_one(self, id):
        fetch_sql = f"SELECT {MemberPointLevelObj.to_string(True)} FROM `mem_member_point_level` WHERE 1 = 1 " \
                    f" AND `id` = \'{id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res = [MemberPointLevelObj.load_db_2_dict(item) for item in items]
                return {"code": 200, "data": res}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def get_level_with_points(self, point: int):
        res = {}
        fetch_sql = f" SELECT {MemberPointLevelObj.to_string(True)} FROM mem_member_point_level " \
                    f" WHERE `points` > {point} " \
                    f" ORDER BY `points` ASC LIMIT 1 "
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res["id"] = items[0][0]
                res["points"] = items[0][1]
                res["level"] = items[0][2]
                res["key"] = items[0][3]
                return {'code': 200, 'data': res, 'message': ""}
            else:
                return {'code': 200, 'data': None, 'message': ""}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def get_level_with_keys(self, key: str):
        res = {}
        fetch_sql = f" SELECT {MemberPointLevelObj.to_string(True)} FROM mem_member_point_level WHERE `key` = \`{key}\`"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res["id"] = items[0][0]
                res["points"] = items[0][1]
                res["level"] = items[0][2]
                res["key"] = items[0][3]
                return {'code': 200, 'data': res, 'message': ""}
            else:
                return {'code': 200, 'data': None, 'message': ""}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def add_pointLevel_point(self, point_level: object):
        try:
            add_check = self.count_one(id=point_level['id'])
            if add_check:
                return {"code": 203, "data": None}
            # print(json.dumps(pointLevel, sort_keys=True, ensure_ascii=False, indent=4))
            insert_sql = f" INSERT INTO `mem_member_point_level` ({MemberPointLevelObj.to_string(False)}) " \
                         " VALUES ( %s )" % MemberPointLevelObj.concat_datas(point_level)
            self.conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def update_pointLevel_point(self, point_level, id):
        try:
            add_check = self.count_one(id=point_level['id'])
            if not add_check:
                return {"code": 404, "data": None}
            old_pointLevel = self.fetch_one(id=point_level['id'])
            update_str = MemberPointLevelObj.split_params(point_level)
            update_sql = f" UPDATE `mem_member_point_level` SET %s " \
                         f" WHERE `id`= %d" % (update_str, id)
            self.conn.sql_commit(update_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def drop_pointLevel_point(self, id):
        add_check = self.count_one(id=id)
        if not add_check:
            return {"code": 404, "data": None}
        execute_SQL = f" DELETE FROM `mem_member_point_level` WHERE `id` = \'{id}\'"
        self.conn.sql_commit(execute_SQL)
        return {"code": 200, "data": None}

    def count_one(self, id) -> bool:
        fetch_sql = f"SELECT count(`id`) FROM `mem_member_point_level` WHERE 1 = 1 " \
                    f" AND `id` = \'{id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                return items[0][0] > 0
            return False
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}
